//
//  SSNDBAppDelegate.m
//  SSNDB
//
//  Created by nako on 9/16/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SSNDBAppDelegate.h"
#import "RootViewController.h"
#import "Person.h"
#import "Contact.h"
#import "SSNXMLParser.h"

#import "zlib.h"
#import "zconf.h"


@implementation SSNDBAppDelegate

@synthesize window;
@synthesize navigationController;
@synthesize databasePath;
@synthesize persons;
@synthesize contacts;
@synthesize readSQL;

#pragma mark -
#pragma mark Application lifecycle

- (BOOL)unzipXmlFile{
	//NSFileManager* fileManager = [NSFileManager defaultManager];
	NSArray *filePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDir = [filePath objectAtIndex:0];
	NSString *tmpPath = [documentsDir stringByAppendingPathComponent:@"SSNDB.xml.zip"];
	NSString *tmpPath2 = [documentsDir stringByAppendingPathComponent:@"unzipTest"];
	//[fileManager createDirectoryAtPath:tmpPath attributes:nil];

	ZipArchive *zip = [[ZipArchive alloc] init];	

	BOOL result = NO;
	
	if([zip UnzipOpenFile:tmpPath]) {
		//zip file is there
		if ([zip UnzipFileTo:tmpPath2 overWrite:YES]) {
			//unzipped successfully
			//NSLog(@"Archive unzip Success");
			result= YES;
		} else {
			//NSLog(@"Failure To Extract Archive, maybe password?");
		}
	} else  {
		//NSLog(@"Failure To Open Archive");
	}
	
	//do cleanup
	//[fileManager removeItemAtPath:tmpPath error:NULL];
	[zip release];
	
	return result;
}

- (BOOL)application:(UIApplication *)application 
	didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
	if( [self unzipXmlFile] == YES){
		databaseName = @"/unzipTest/SSNDB.xml";
		//databaseName = @"SSNDB.xml";
		NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
		NSString *documentsDir = [documentPaths objectAtIndex:0];
		databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
		//NSLog(@"%@",databasePath);
		[self checkAndCreateDatabase];
		[self SSNParseXML];
		readSQL = NO;
	}else{
	
	/* sqlite3 db read
    // Override point for customization after application launch.
    databaseName = @"SSNDB.sqlite";
	
	// Get the path to the documents directory and append the databaseName
	NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDir = [documentPaths objectAtIndex:0];
	databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
	
	// Execute the "checkAndCreateDatabase" function
	[self checkAndCreateDatabase];
	
	// Query the database for all animal records and construct the "animals" array
	[self readSSNFromDatabase];
	*/
		readSQL = YES;
	}
	NSLog(@" readSQL %@",[self readSQL]? @"YES":@"NO");
    // Set the navigation controller as the window's root view controller and display.
    
	RootViewController *controller = 
	[[RootViewController alloc]
	 initWithNibName:@"RootViewController"
	 bundle:nil];
	
	UINavigationController *navController =
	[[UINavigationController alloc] 
	 initWithRootViewController:controller];
	
	self.navigationController = navController;
	
	[navController release];
	[controller release];
	
	[window addSubview:self.navigationController.view];
	
	[self.window makeKeyAndVisible];

    return YES;
}


-(void) checkAndCreateDatabase{
	// Check if the SQL database has already been saved to the users phone, if not then copy it over
	BOOL success;
	
	// Create a FileManager object, we will use this to check the status
	// of the database and to copy it over if required
	NSFileManager *fileManager = [NSFileManager defaultManager];
	
	// Check if the database has already been created in the users filesystem
	success = [fileManager fileExistsAtPath:databasePath];

	// If the database already exists then return without doing anything
	if(success) return;
	
	// If not then proceed to copy the database from the application to the users filesystem
	
	// Get the path to the database in the application package
	NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
	
	// Copy the database from the package to the users filesystem
	[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
	
	[fileManager release];
}

-(void) SSNParseXML {
	NSURL *xmlURL = [NSURL fileURLWithPath:databasePath];
	//NSLog(@"%@",databasePath);
	NSXMLParser *xmlParser = [[NSXMLParser alloc]initWithContentsOfURL:xmlURL];
	
	SSNXMLParser *ssnXMLParser = [[SSNXMLParser alloc] initXMLParser];
	
	[xmlParser setDelegate:ssnXMLParser];
	
	// Init the persons & contacts Array
	persons = [[NSMutableArray alloc] init];
	contacts = [[NSMutableArray alloc] init];
	
	BOOL success = [xmlParser parse];
	
	if( success ){
		//NSLog(@"Parse Success");
	}else {
		//NSLog(@"Error Parse");
	}
	/*
	for (int i = 0; i < [self.persons count]; i++) {
		Person *thisPerson = [self.persons objectAtIndex:i];
		NSLog(@" %@ %@ %@ %@",thisPerson.Name,thisPerson.SSN,thisPerson.Telephone,thisPerson.Address);
	}
	
	for (int i = 0; i < [self.contacts count]; i++) {
		Contact *thisContact = [self.contacts objectAtIndex:i];
		NSLog(@" %@ %@ %@",thisContact.SSN,thisContact.Contact_date,thisContact.Note);
	}
	*/
	
}
-(void) readSSNFromDatabase {
	// Setup the database object
	sqlite3 *database;
	
	// Init the persons & contacts Array
	persons = [[NSMutableArray alloc] init];
	contacts = [[NSMutableArray alloc] init];
	
	// Open the database from the users filessytem
	if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
		// Setup the SQL Statement and compile it for faster access
		const char *sqlStatement = "select * from person";
		sqlite3_stmt *compiledStatement;
		if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
			// Loop through the results and add them to the feeds array
			while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
				// Read the data from the result row
				NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
				NSString *aSSN = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
				NSString *aTelephone = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
				NSString *aAddress = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
				// Create a new person object with the data from the database
				Person *person = [[Person alloc] initWithName:aName ssn:aSSN telephone:aTelephone address:aAddress];
				//NSLog(@"%@ %@ %@ %@",aName,aSSN,aTelephone,aAddress);
				// Add the person object to the persons Array
				[persons addObject:person];
				
				[person release];
			}
		}
		
		// Release the compiled statement from memory
		sqlite3_finalize(compiledStatement);
		compiledStatement = nil;
		
		sqlStatement = "select * from contact";
		if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
		
			while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
				NSString *aSSN = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
				NSString *aContact_date = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
				NSString *aNote = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
				
				// Create a new person object with the data from the database
				Contact *contact = [[Contact alloc] initWithName:aSSN contact_date:aContact_date note:aNote];
				
				// Add the person object to the persons Array
				[contacts addObject:contact];
				
				[contact release];
			}
		 
		 }
		// Release the compiled statement from memory
		sqlite3_finalize(compiledStatement);
		compiledStatement = nil;	
		
	}
	sqlite3_close(database);
	
}


- (void)applicationWillResignActive:(UIApplication *)application {
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    /*
     Called as part of  transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
     */
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}


- (void)applicationWillTerminate:(UIApplication *)application {
    /*
     Called when the application is about to terminate.
     See also applicationDidEnterBackground:.
     */
}


#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    /*
     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
     */
}


- (void)dealloc {
	[databasePath release];
	[persons release];
	[contacts release];
	[navigationController release];
	[window release];
	[super dealloc];
}


@end

